package com.diorsunion.hedge.io;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * Created by custe on 2016/5/29.
 */
public interface MessageBO {

    Map<String,List<MessageHandler>> getMessageHandlerMap();

    default void initHandler(MessageHandler messageHandler){
        if(messageHandler==null){
            return;
        }
        Map<String,List<MessageHandler>> map = getMessageHandlerMap();
        List<Class> classSet= messageHandler.handlerClasses();
        for(Class clazz:classSet ){
            String className = clazz.getName();
            List<MessageHandler> messageHandlerList = map.get(className);
            if(messageHandlerList==null){
                messageHandlerList = Lists.newArrayList();
            }
            messageHandlerList.add(messageHandler);
            map.put(className,messageHandlerList);
        }

    }

    default List<Message> execute(Serializable obj) {
        List<Message> resultList = Lists.newArrayList();
        if(obj==null){
            return resultList;
        }
        String className = obj.getClass().getName();
        List<MessageHandler> messageHandlerSet = getMessageHandlerMap().get(className);
        if(!CollectionUtils.isEmpty(messageHandlerSet)){
            messageHandlerSet.parallelStream().forEach(x->resultList.add(x.execute(obj)));
        }
        return resultList;
    }
}
